import sys
import os
sys.path.append(os.path.abspath(os.path.dirname(__file__)) + "/..")
from stock.simulatestock import *
from utils.smtp.smtp import *
from utils.utils import *
import time

last_price = 1.458
code = "sz159920"
cycle = 5
num = 2
grid_rate = 0.005

def grid_get_cur_price():
    data = get_url_data(get_url(code, cycle, num))
    return float(data[-1]["close"])

def grid_monitor():
    # 判断下时间
    if work_time_check() == False:
        # print("err time")
        return
    global last_price
    cur = grid_get_cur_price()
    if last_price == 0:
        last_price = cur

    # print(cur*grid_rate)
    # smtp = Smtp()
    # smtp.Send(
    #     "%s need goto sell one grid price = %-04f"%(code, cur)
    # )

    # print("pri=%.3f"%(cur))
    cur_rate = (cur - last_price)/last_price
    if cur_rate >= grid_rate:
        smtp = Smtp()
        str = "%s need goto sell one grid price = %-04f"%(code, cur)
        print(str)
        smtp.Send(
            str
        )
        last_price = cur
    elif cur_rate <= -grid_rate:
        smtp = Smtp()
        str = "%s need goto buy one grid price = %-04f"%(code, cur)
        print(str)
        smtp.Send(
            str
        )
        last_price = cur
    else:
        pass


if __name__ == "__main__":
    while True:
        try:
            grid_monitor()
        except :
            print("catch err*****************")
        else:
            pass
        time.sleep(10)
